// Copyright © 2023 Cisco Systems, Inc. and its affiliates.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package exploits

import (
	"sort"
	"strings"
	"testing"

	vulnerabilitytypes "github.com/openclarity/openclarity/scanner/families/vulnerabilities/types"
)

func Test_getCVEIDsFromVulnerabilitiesResults(t *testing.T) {
	type args struct {
		vulnResults *vulnerabilitytypes.Result
	}
	tests := []struct {
		name     string
		args     args
		wantCves string
	}{
		{
			name: "nil vulnResults",
			args: args{
				vulnResults: nil,
			},
			wantCves: "",
		},
		{
			name: "nil  VulnerabilitiesByKey",
			args: args{
				vulnResults: &vulnerabilitytypes.Result{
					VulnerabilitiesByKey: nil,
				},
			},
			wantCves: "",
		},
		{
			name: "no vulnerabilities",
			args: args{
				vulnResults: &vulnerabilitytypes.Result{
					VulnerabilitiesByKey: map[vulnerabilitytypes.VulnerabilityKey]vulnerabilitytypes.Vulnerability{},
				},
			},
			wantCves: "",
		},
		{
			name: "sanity",
			args: args{
				vulnResults: &vulnerabilitytypes.Result{
					VulnerabilitiesByKey: map[vulnerabilitytypes.VulnerabilityKey]vulnerabilitytypes.Vulnerability{
						"vul1": {ID: "cve1"},
						"vul2": {ID: "cve3"},
					},
					Source: vulnerabilitytypes.Source{},
				},
			},
			wantCves: "cve1,cve3",
		},
		{
			name: "same cve id in different vulnerabilities",
			args: args{
				vulnResults: &vulnerabilitytypes.Result{
					VulnerabilitiesByKey: map[vulnerabilitytypes.VulnerabilityKey]vulnerabilitytypes.Vulnerability{
						"vul1": {ID: "cve1"},
						"vul2": {ID: "cve1"},
					},
					Source: vulnerabilitytypes.Source{},
				},
			},
			wantCves: "cve1",
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			gotCves := getCVEIDsFromVulnerabilitiesResults(tt.args.vulnResults)
			sortedGotCves := sortCVEString(gotCves)
			if sortedGotCves != tt.wantCves {
				t.Errorf("getCVEIDsFromVulnerabilitiesResults() = %v, want %v", sortedGotCves, tt.wantCves)
			}
		})
	}
}

func sortCVEString(cves string) string {
	arr := strings.Split(cves, ",")

	sort.Slice(arr, func(i, j int) bool {
		return arr[i] < arr[j]
	})

	return strings.Join(arr, ",")
}
